package operations;

import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-07-07
 * Time: 22:07
 */
public class DeleteOperation implements IOperation{
    public void work(BookList bookList) {
        int sz = bookList.getBookSize();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要删除的图书的名字：");
        String name = scanner.nextLine();
        int i = 0;
        int pos = -1;
        //开始找要删除图书的位置，找到了就退出循环
        for (; i < sz; i++) {
            if(bookList.getBook(i).getName().equals(name)) {
                pos = i;
                break;
            }
        }
        //i = sz说明书架遍历结束，但未找到图书的位置，那么书架上没有该图书
        if(i == sz) {
            System.out.println("书架上没有你要删除的图书。");
            return;
        }

        //若该图书在书架上，则将它后面的图书前移
        for (int j = pos; j < sz - 1; j++) {       //这里j < sz-1，如果是 j < sz 会导致越界访问！！！
            bookList.setBooks(j,bookList.getBook(j+1));
        }
        //图书数-1
        bookList.setBookSize(sz - 1);
        System.out.println("删除完成！");
    }
}
